package jsyf.oa.service.psi;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.psi.GoodsDao;
import jsyf.oa.dao.psi.InventoryDao;
import jsyf.oa.dao.psi.PurchaseDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.psi.InventoryEntity;
import jsyf.oa.entity.psi.PurchaseEntity;
import jsyf.oa.entity.psi.PurchaseManiEntity;
import jsyf.oa.entity.system.*;
import jsyf.oa.facade.psi.PurchaseFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;


/**
 * Created by Maqiuqiu on 2018/10/20.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class PurchaseService implements PurchaseFacade {
    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CopierDao copierDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;

    @Override
    public JSONObject save(String jsonData) {
        PurchaseEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), PurchaseEntity.class);
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        if ("0".equals(entity.getMain().getId()) || StringUtils.isBlank(entity.getMain().getId())) {
            purchaseDao.add(entity.getMain());
        } else {
            PurchaseManiEntity purchaseManiEntity =
                    (PurchaseManiEntity) purchaseDao.getIBaseEntityById(entity.getMain().getId());
            purchaseManiEntity.setApplyDate(entity.getMain().getApplyDate());
            purchaseManiEntity.setCompanyId(entity.getMain().getCompanyId());
            purchaseManiEntity.setCompanyName(entity.getMain().getCompanyName());
            purchaseManiEntity.setDepartId(entity.getMain().getDepartId());
            purchaseManiEntity.setDepartName(entity.getMain().getDepartName());
            purchaseManiEntity.setReceiveDate(entity.getMain().getReceiveDate());
            purchaseManiEntity.setPurpose(entity.getMain().getPurpose());
            purchaseManiEntity.setState(entity.getMain().getState());
            purchaseManiEntity.setAuditFlag(entity.getMain().getAuditFlag());
            purchaseManiEntity.setCurrentAuditorId(entity.getMain().getCurrentAuditorId());
            purchaseManiEntity.setCurrentAuditorName(entity.getMain().getCurrentAuditorName());
            purchaseManiEntity.setCopierReturnReason(entity.getMain().getCopierReturnReason());
            purchaseManiEntity.setCreateTime(entity.getMain().getCreateTime());
            purchaseManiEntity.setCreateUserId(entity.getMain().getCreateUserId());
            purchaseManiEntity.setUpdateTime(entity.getMain().getUpdateTime());
            purchaseManiEntity.setUpdateUserId(entity.getMain().getUpdateUserId());
            purchaseManiEntity.setCreateUserName(entity.getMain().getCreateUserName());
            purchaseManiEntity.setMethod(entity.getMain().getMethod());
            purchaseManiEntity.setBuyerUserId(entity.getMain().getBuyerUserId());
            purchaseManiEntity.setBuyerUserName(entity.getMain().getBuyerUserName());
            purchaseManiEntity.setBuyerDate(entity.getMain().getBuyerDate());
            purchaseManiEntity.setBuyerAttachName(entity.getMain().getBuyerAttachName());
            purchaseManiEntity.setBuyerAttachUrl(entity.getMain().getBuyerAttachUrl());
            purchaseManiEntity.setInRepoDate(entity.getMain().getInRepoDate());
            purchaseManiEntity.setInUserId(entity.getMain().getInUserId());
            purchaseManiEntity.setInUserName(entity.getMain().getInUserName());
            purchaseDao.update(purchaseManiEntity);
        }
        //保存库存表信息
        inventoryDao.removeByCondition("AND PURCHASE_ID = ?",new String[]{entity.getMain().getId()});
        List<JSONObject> entityList = entity.getGoodsInfo();
        for (int i = 0; i < entityList.size(); i++) {
            JSONObject jsonObject = entityList.get(i);
            InventoryEntity inventoryEntity = new InventoryEntity();
            inventoryEntity.setGoodsId(jsonObject.getString("goodsId"));
            inventoryEntity.setCount(Integer.valueOf(jsonObject.getString("count")));
            inventoryEntity.setPrice(jsonObject.getString("price"));
            inventoryEntity.setUnit(jsonObject.getString("unit"));
            inventoryEntity.setRequirements(jsonObject.getString("requirements"));
            inventoryEntity.setExtra(jsonObject.getString("extra"));
            inventoryEntity.setAddress("");
            inventoryEntity.setState("-1");
            inventoryEntity.setPurchaseId(entity.getMain().getId());
            inventoryEntity.setRepoInOutId("");
            inventoryEntity.setCreateUserId(entity.getMain().getCreateUserId());
            inventoryEntity.setCreateTime(entity.getMain().getCreateTime());
            inventoryEntity.setUpdateUserId(entity.getMain().getUpdateUserId());
            inventoryEntity.setUpdateTime(entity.getMain().getUpdateTime());
            inventoryDao.add(inventoryEntity);
        }

        //保存审核人信息
        if ("0".equals(entity.getMain().getId()) || StringUtils.isBlank(entity.getMain().getId())) {
            //新建-> 直接保存审核人 和抄送人
            saveAuditorsAndCopier(entity.getMain(), jsonObjectList);
        } else {
            //编辑-> 先刪除审核表，重新保存
            delAuditorsAndCopier(entity.getMain().getId());
            saveAuditorsAndCopier(entity.getMain(),jsonObjectList);
        }
        //保存抄送人信息
        copierDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{entity.getMain().getId()});
        List<CopierEntity> copierEntityList = entity.getCopiers();
        for (int i = 0; i < copierEntityList.size(); i++) {
            CopierEntity copierEntity = copierEntityList.get(i);
            copierEntity.setMainId(entity.getMain().getId());
            copierEntity.setModuleName("purchaseType");
            copierDao.add(copierEntityList.get(i));
        }
        result.put("message", jsonObjectList);
        result.put("mainId", entity.getMain().getId());
        return result;
    }

    @Override
    public Boolean updateBuyInfo(String jsonData){
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        PurchaseManiEntity purchaseManiEntity =
                (PurchaseManiEntity) purchaseDao.getIBaseEntityById(jsonParams.getString("id"));
        purchaseManiEntity.setBuyerUserId(jsonParams.getString("buyerUserId"));
        purchaseManiEntity.setBuyerUserName(jsonParams.getString("buyerUserName"));
        purchaseManiEntity.setBuyerDate(jsonParams.getString("buyerDate"));
        purchaseManiEntity.setBuyerAttachName(jsonParams.getString("attachName"));
        purchaseManiEntity.setBuyerAttachUrl(jsonParams.getString("attachUrl"));
        purchaseManiEntity.setState("1");
        purchaseDao.update(purchaseManiEntity);
        return true;
    }

    @Override
    public Boolean updateState(String jsonData){
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String flag = jsonParams.getString("flag");
        String inRepoDate = jsonParams.getString("inRepoDate");
        String inUserId = jsonParams.getString("inUserId");
        String inUserName = jsonParams.getString("inUserName");
        PurchaseManiEntity purchaseManiEntity =
                (PurchaseManiEntity) purchaseDao.getIBaseEntityById(jsonParams.getString("id"));
        if(flag.equals("1")){
            purchaseManiEntity.setState("2");
            purchaseManiEntity.setInRepoDate("");
            purchaseManiEntity.setInUserId("");
            purchaseManiEntity.setInUserName("");
        }else {
            purchaseManiEntity.setState("3");
            purchaseManiEntity.setInRepoDate(inRepoDate);
            purchaseManiEntity.setInUserId(inUserId);
            purchaseManiEntity.setInUserName(inUserName);
        }
        purchaseDao.update(purchaseManiEntity);
        return true;
    }

    private void saveAuditorsAndCopier(PurchaseManiEntity main,List<JSONObject> jsonObjectList) {
        List<AuditEntity> auditList = new ArrayList<>();
        List<CopierEntity> copierList = new ArrayList<>();
        //查询总经理
        String allParentStr = checkDao.getParentByUserId(main.getCreateUserId(), true);
        String[] allParentArr = allParentStr.split(",");
        boolean hasZongJingLi = false;
        //按主职位查
        for (int i = 0; i < allParentArr.length; i++) {
            List<JSONObject> objectList =
                    userDao.getViewByUserId(" AND id = ? AND main=1 AND jobState !=1",
                            new Object[]{allParentArr[i].substring(1, allParentArr[i].length() - 1)});
            if (objectList != null && objectList.size() > 0) {
                JSONObject jsonObject = objectList.get(0);
                if (jsonObject.getString("roleName").equals("总经理")) {
                    AuditEntity firstAuditor = new AuditEntity();
                    firstAuditor.setAuditorId(jsonObject.getString("id"));
                    firstAuditor.setAuditorName(jsonObject.getString("name"));
                    firstAuditor.setRoleName((jsonObject.getString("roleName")));
                    firstAuditor.setAuditFlag(-1);
                    firstAuditor.setAuditSort(0);
                    firstAuditor.setMainId(main.getId());

                    auditList.add(firstAuditor);
                    hasZongJingLi = true;
                }
//                if (jsonObject.getString("roleName").equals("总经理")) {
//                    CopierEntity copierEntity = new CopierEntity();
//                    copierEntity.setCopierId(jsonObject.getString("id"));
//                    copierEntity.setCopierName(jsonObject.getString("name"));
//                    copierEntity.setMainId(main.getId());
//
//                    copierList.add(copierEntity);
//                }
            }
        }
        //按兼职位查
        if (hasZongJingLi) {

        } else {
            for (int i = 0; i < allParentArr.length; i++) {
                List<JSONObject> objectList =
                        userDao.getViewByUserId(" AND id = ? AND main=0 AND jobState !=1",
                                new Object[]{allParentArr[i].substring(1, allParentArr[i].length() - 1)});
                if (objectList != null && objectList.size() > 0) {
                    for (int j = 0; j < objectList.size(); j++) {
                        JSONObject jsonObject = objectList.get(j);
                        if (jsonObject.getString("roleName").equals("总经理") && !hasZongJingLi) {
                            AuditEntity firstAuditor = new AuditEntity();
                            firstAuditor.setAuditorId(jsonObject.getString("id"));
                            firstAuditor.setAuditorName(jsonObject.getString("name"));
                            firstAuditor.setRoleName((jsonObject.getString("roleName")));
                            firstAuditor.setAuditFlag(-1);
                            firstAuditor.setAuditSort(0);
                            firstAuditor.setMainId(main.getId());

                            auditList.add(firstAuditor);
                            hasZongJingLi = true;
                        }
                    }
                }
            }
        }
        AuditEntity lastAuditor = new AuditEntity();
        lastAuditor.setAuditorId("201711271733404C9DA1461F2421F828");
        lastAuditor.setAuditorName("曹国玉");
        lastAuditor.setRoleName("后台管理");
        lastAuditor.setAuditFlag(-1);
        lastAuditor.setAuditSort(1);
        lastAuditor.setMainId(main.getId());


        auditList.add(lastAuditor);
        //去除重复的审核人
        List<AuditEntity> tempList = new ArrayList<>();
        String idStr = "";
        for (int i = 0; i < auditList.size(); i++) {
            if (!idStr.contains(auditList.get(i).getAuditorId())) {
                idStr += auditList.get(i).getAuditorId() + ",";
                tempList.add(auditList.get(i));
            }
        }
        auditList = tempList;
        //去除重复的抄送人
        List<CopierEntity> temp2List = new ArrayList<>();
        String id2Str = "";
        for (int i = 0; i < copierList.size(); i++) {
            if (!id2Str.contains(copierList.get(i).getCopierId())) {
                id2Str += copierList.get(i).getCopierId() + ",";
                temp2List.add(copierList.get(i));
            }
        }
        copierList = temp2List;
        for (int i = 0; i < copierList.size(); i++) {
            copierDao.add(copierList.get(i));
        }
        //排序
        Collections.sort(auditList, new Comparator<AuditEntity>() {

            @Override
            public int compare(AuditEntity o1, AuditEntity o2) {
                return o1.getAuditSort().compareTo(o2.getAuditSort());// 按照sortNo升序
            }
        });
        for (int i = 0; i < auditList.size(); i++) {
            auditDao.add(auditList.get(i));
        }
        //设置当前审核人
        setCurrentAuditor(main, auditList.get(0),jsonObjectList);
    }

    //删除审核人和抄送人
    private void delAuditorsAndCopier(String mainId) {
        auditDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{mainId});
        copierDao.removeByCondition(" AND MAIN_ID = ? ", new String[]{mainId});
    }

    //更新主表 审核人和审核表的第一审核人
    private void setCurrentAuditor(PurchaseManiEntity main, AuditEntity currentAuditor,List<JSONObject> jsonObjectList) {
        //List<JSONObject> jsonObjectList = new ArrayList<>();
        main.setCurrentAuditorId(currentAuditor.getAuditorId());
        main.setCurrentAuditorName(currentAuditor.getAuditorName());
        //currentAuditor.setAuditFlag(0);
        currentAuditor.setAuditFlag(Integer.valueOf(main.getAuditFlag()));
        purchaseDao.update(main);
        auditDao.update(currentAuditor);

        //企业号:给第一审核人发送消息
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", main.getCurrentAuditorId());
        msgObject.put("content", String.format(PSI_AUDIT_AUDIT,
                main.getCurrentAuditorName(),
                main.getCreateUserName(),
                DateUtils.parse(main.getUpdateTime(), "yyyy-MM-dd HH:mm")
        ));
        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

        //保存消息到消息表t_sys_message
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setCreateUserId(main.getCreateUserId());
        messageEntity.setCreateTime(purchaseDao.getCurrentTime());
        messageEntity.setContent(String.format(PSI_AUDIT_ONE,main.getCreateUserName()));
        messageEntity.setMessageType(1);
        messageEntity.setMainId(main.getId());
        messageEntity.setDelFlag(0);
        messageEntity.setOpenUrl("/page/psi/purchase.html");
        messageEntity.setOpenTitle(String.format(PSI_AUDIT_ONE,main.getCreateUserName()));
        messageDao.add(messageEntity);

        //保存第一审核人信息到消息收件人表t_sys_message_receiver
        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
        messageReceiverEntity.setMessageId(messageEntity.getId());
        messageReceiverEntity.setUserId(main.getCreateUserId());
        messageReceiverEntity.setUserType(0);
        messageReceiverEntity.setReadFlag(0);
        messageReceiverDao.add(messageReceiverEntity);

        //发消息
        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
    }

    @Override
    public Boolean delById(String id) {
        return purchaseDao.delById(id) > 0;
    }

    @Override
    public Boolean removeById(String id) {
        return purchaseDao.removeById(id) > 0;
    }

    @Override
    public JSONObject getPurchaseList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String key = jsonParams.getString("key");
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        condition.append(" ORDER BY t_psi_purchase.CREATE_TIME DESC   ");
        //查询list
        List<JSONObject> records = purchaseDao.getPurchaseList(userId,condition.toString(),requestPage,pageSize);
        for (int i = 0; i < records.size(); i++) {
            JSONObject jsonObject = records.get(i);
            List<JSONObject> objectList = purchaseDao.getGoodsInfo(jsonObject.getString("id"));
            jsonObject.put("goodsInfo",objectList);
        }
        //查询总数
        int recordCount = purchaseDao.getPurchaseList(userId,condition.toString(), 1, Integer.MAX_VALUE).size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        //子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getPurchaseById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject results = new JSONObject();
        String id = jsonParams.getString("id");
        JSONObject result = purchaseDao.getJSONById(id);
        List<JSONObject> goodsInfo = purchaseDao.getGoodsInfo(id);
        for (int i = 0; i < goodsInfo.size(); i++) {
            JSONObject jsonObject = goodsInfo.get(i);
            jsonObject.put("goodsName",goodsDao.getJSONById(jsonObject.getString("goodsId")).getString("name"));
        }
        List<JSONObject> auditors =
                auditDao.getJSONListByCondition(" and MAIN_ID = ? ORDER BY AUDIT_SORT", new Object[]{id});
        List<JSONObject> copiers =
                copierDao.getJSONListByCondition(" and MAIN_ID = ?", new Object[]{id});
        List<JSONObject> auditHistorys =
                auditHistoryDao.getJSONListByCondition(" AND MAIN_ID = ? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id});
        results.put("main", result);
        results.put("goodsInfo",goodsInfo);
        results.put("auditors", auditors);
        results.put("copiers", copiers);
        results.put("auditHistorys", auditHistorys);
        return results;
    }

    @Override
    public JSONObject applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        JSONObject result = new JSONObject();
        String id = jsonPalams.getString("id");
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String userName = jsonPalams.getString("userName");//当前审核人NAME
        String roleName = jsonPalams.getString("roleName");//当前审核人ROLENAME
        String advise = jsonPalams.getString("advise");//意见
        PurchaseManiEntity purchaseManiEntity = (PurchaseManiEntity) purchaseDao.getIBaseEntityById(id);
        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userName);
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
        auditHistoryEntity.setAuditType(8);
        auditHistoryDao.add(auditHistoryEntity);
        //更新当前审核人的--审核表记录
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object)
                auditDao.getIBaseEntityByCondition(" and MAIN_ID = ? and AUDITOR_ID = ? ", new Object[]{id, userId});
        if (null != auditEntityList && auditEntityList.size() > 0) {
            AuditEntity auditEntity = auditEntityList.get(0);
            auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
            auditEntity.setAuditAdvise(advise);
            auditEntity.setAuditTime(auditDao.getCurrentTime());
            auditEntity.setAuditorName(userName);
            auditEntity.setRoleName(roleName);
            auditDao.update(auditEntity);
        }
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        List<AuditEntity> auditList =  (List<AuditEntity>) (Object)
                auditDao.getIBaseEntityByCondition("and MAIN_ID = ?  order by audit_sort", new Object[]{id});
        for (int i = 0; i < auditList.size(); i++) {
            AuditEntity audit = auditList.get(i);
            if (audit.getAuditorId().equals(userId)) {
                //如果是驳回，修改主表状态为驳回->2
                if (auditFlag.equals("2")) {
                    purchaseManiEntity.setAuditFlag(auditFlag);
                    purchaseDao.update(purchaseManiEntity);

                    //企业号:审核驳回，发消息通知申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", purchaseManiEntity.getCreateUserId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(TRUCK_AUDIT_REJECT,
                            purchaseManiEntity.getCreateUserName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //审核驳回，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity messageCreateEntity = new MessageEntity();
                    messageCreateEntity.setCreateUserId(purchaseManiEntity.getCreateUserId());
                    messageCreateEntity.setCreateTime(purchaseDao.getCurrentTime());
                    messageCreateEntity.setContent(String.format(PSI_AUDIT_REJECT,
                            purchaseManiEntity.getCreateUserName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    messageCreateEntity.setMessageType(0);
                    messageCreateEntity.setMainId(id);
                    messageCreateEntity.setDelFlag(0);
                    messageCreateEntity.setOpenUrl("/page/psi/purchase.html?id="
                            + purchaseManiEntity.getId() + "&pageType=look");
                    messageCreateEntity.setOpenTitle(String.format(PSI_AUDIT_THREE, audit.getAuditorName()));
                    messageDao.add(messageCreateEntity);

                    //审核驳回，发送消息给申请人,保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageCreateReceiverEntity = new MessageReceiverEntity();
                    messageCreateReceiverEntity.setMessageId(messageCreateEntity.getId());
                    messageCreateReceiverEntity.setUserId(purchaseManiEntity.getCreateUserId());
                    messageCreateReceiverEntity.setUserType(2);
                    messageCreateReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageCreateReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageCreateEntity, messageCreateReceiverEntity));
                    break;
                }
                //如果是最后一个人审核通过，标记主表状态为通过->1
                if (auditList.size() - 1 == i) {
                    purchaseManiEntity.setAuditFlag("1");
                    purchaseManiEntity.setState("0");
                    purchaseDao.update(purchaseManiEntity);
                    //企业号: 最后一个审核通过,发送消息给申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", purchaseManiEntity.getCreateUserId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(PSI_AUDIT_PASS,
                            purchaseManiEntity.getCreateUserName(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //审核通过，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity msgAuditEntity = new MessageEntity();
                    msgAuditEntity.setCreateUserId(purchaseManiEntity.getCreateUserId());
                    msgAuditEntity.setCreateTime(purchaseDao.getCurrentTime());
                    msgAuditEntity.setContent(String.format(PSI_AUDIT_PASS,
                            purchaseManiEntity.getCreateUserName(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    msgAuditEntity.setMessageType(0);
                    msgAuditEntity.setMainId(id);
                    msgAuditEntity.setDelFlag(0);
                    msgAuditEntity.setOpenUrl("/page/psi/purchase.html?id="
                            + purchaseManiEntity.getId() + "&pageType=look");
                    msgAuditEntity.setOpenTitle(String.format(PSI_AUDIT_TWO, audit.getAuditorName()));
                    messageDao.add(msgAuditEntity);

                    //审核通过，发送消息给申请人，保存消息到表t_sys_message_receiver
                    MessageReceiverEntity msgReceiverEntity = new MessageReceiverEntity();
                    msgReceiverEntity.setMessageId(msgAuditEntity.getId());
                    msgReceiverEntity.setUserId(purchaseManiEntity.getCreateUserId());
                    msgReceiverEntity.setUserType(2);
                    msgReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(msgReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(msgAuditEntity, msgReceiverEntity));
                }
            } else {
                //下一位审核人才进入，修改审核表状态和主表审核人信息
                if (audit.getAuditFlag().toString().equals("-1")) {
                    audit.setAuditFlag(0);
                    auditDao.update(audit);
                    purchaseManiEntity.setCurrentAuditorName(audit.getAuditorName());
                    purchaseManiEntity.setCurrentAuditorId(audit.getAuditorId());
                    purchaseManiEntity.setAuditFlag(audit.getAuditFlag().toString());
                    purchaseDao.update(purchaseManiEntity);
                    break;
                }
            }
        }
        //发消息
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }

}
